import Ajax from 'axios'
import qs from 'qs'
import setting from '@/settings'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { Message } from 'element-ui'

const ajax = Ajax.create()
ajax.interceptors.request.use(function(config) {
  config.headers.Authorization = 'Bearer ' + getToken()
  return config
})
ajax.interceptors.response.use(function(response) {
  return response
}, function(error) {
  if (process.env.NODE_ENV === 'development') console.log(error)
  if (error.response.data.message === 'Unauthenticated.') {
    removeToken()
    router.push('/login')
  }
  return Promise.reject(error.response)
})

/**
 * post请求
 * @param action
 * @param param
 * @method post OR get
 * @returns {Promise<AxiosResponse<T>>}
 */
export const post = function(action, param) {
  let url = process.env.NODE_ENV === 'production' ? setting.baseUrl.pro : setting.baseUrl.dev
  url += action
  return ajax.post(url, qs.stringify(param))
}

/**
 * get 请求
 * @param action
 * @param param
 * @returns {Promise<AxiosResponse<T>>}
 */
export const get = function(action, param) {
  let url = process.env.NODE_ENV === 'production' ? setting.baseUrl.pro : setting.baseUrl.dev
  url += action
  if (param) {
    url += '?' + qs.stringify(param)
  }
  return ajax.get(url)
}

/**
 * PUT请求
 * @param action
 * @param param
 * @method post OR get
 * @returns {Promise<AxiosResponse<T>>}
 */
export const put = function(action, param) {
  let url = process.env.NODE_ENV === 'production' ? setting.baseUrl.pro : setting.baseUrl.dev
  url += action
  return ajax.put(url, qs.stringify(param))
}

/**
 * delete删除请求
 * @param action
 * @param param
 * @returns {AxiosPromise}
 */
export const del = function(action, param) {
  let url = process.env.NODE_ENV === 'production' ? setting.baseUrl.pro : setting.baseUrl.dev
  url += action
  return ajax.delete(url, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }, qs.stringify(param))
}

export const upload = function(action, data, uploading) {
  const url = process.env.NODE_ENV === 'production' ? setting.baseUrl.pro : setting.baseUrl.dev
  console.log(data)
  return ajax.post(
    url + action,
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progress) => {
        uploading && uploading({ total: progress.total, loaded: progress.loaded })
      }
    }
  )
}

/**
 * 上传文件所需参数
 * @returns {{headers: {Authorization: string}, url: string}}
 */
export const uploadParams = function(action) {
  return {
    url: process.env.NODE_ENV === 'production' ? setting.baseUrl.pro + action : setting.baseUrl.dev + action,
    headers: {
      'Authorization': 'Bearer ' + getToken()
    }
  }
}

/**
 * 请求返回的错误处理
 * @param error
 */
export const handleError = function(error) {
  const { message, errors } = error.data
  if (errors) {
    for (const attr in errors) {
      Message({
        message: errors[attr][0],
        type: 'error'
      })
      return
    }
  } else if (message) {
    Message({
      message,
      type: 'error'
    })
  } else {
    Message({
      message: error.data,
      type: 'error'
    })
  }
}

export default { post, get }
